import wx
from wx._core import wxAssertionError
from io import BytesIO
import re
import threading
import os
import requests
import json
import base64
import rsa

import mydata
import mysqldb
import myimage
#filepath = os.path.dirname(os.path.abspath(sys.argv[0]))


class mythread(threading.Thread):
    def __init__(self,windows,defrun,code):
        threading.Thread.__init__(self)
        self.windows = windows
        self.defrun = defrun
        self.code = code

    def run(self):
        self.defrun(self.code,self.windows)


def creat_dir_file(mypath):
    if not os.path.exists(mypath):
        os.mkdir(mypath)


def pngSize(width,hight,data):
    by = BytesIO(data)
    p = wx.Image(by, type=wx.BITMAP_TYPE_JPEG)
    bgm = p.Scale(width,hight)
    by.close()
    return wx.Bitmap(bgm)


def httpadd(code,windows):
    appid="yktexshikvjg8lnq"
    appsecret="YlViYzFob3F2a055VjNMZjQxRHljQT09"
    url = "https://www.mxnzp.com/api/barcode/goods/details?app_id={}&app_secret={}&barcode={}".format(appid,appsecret,code)
    ret = requests.get(url)
    if ret.status_code == 200:
        ret = json.loads(ret.text)
        if ret['code'] == 0:
            wx.CallAfter(windows.LogMesrun,(False,"联网未查询到商品"))
            #windows.rettext.SetLabel("联网未查询到商品")
        elif ret['code'] == 1:
            msg = "null,{},'{}','{}','{}',''".format(code,ret['data']['goodsName'],ret['data']['price'],ret['data']['standard'])
            ret = mysqldb.mysql.insert_data("inventory","ID,myid,name,price,ations,path",msg)
            if ret:
                #wx.CallAfter(windows.LogMesCreate,code)
                wx.CallAfter(windows.LogMesrun,(True,code))
                #windows.rettext.SetLabel("商品添加成功")
                wx.CallAfter(windows.LogMesrun,(False,"商品添加成功"))
    else:
        #windows.rettext.SetLabel("联网添加失败,请重试")
        wx.CallAfter(windows.LogMesrun,(False,"联网添加失败,请重试"))


def ch_zh_sum(m,s=""):
    s += mydata.CH_ZH[m[0]][0]
    d = mydata.CH_ZH[str(len(m))][1]
    if m[0] != "0":
        s += d
    if d == "十":
        if m[-1] == "0":
            return s
        else:
            return s + mydata.CH_ZH[m[-1]][0]
    else:
        return ch_zh_sum(m[1:],s=s)


def ch_zh_han(m):
    if "." in str(m):
        m_str = str(m).split(".")
        try:
            m_str = m_str[0]+ "." + m_str[1][0] if int(m_str[1][1]) < 5 else str(int(m_str[1][0]) + 1)
        except:
            m_str = m_str[0]+ "." + m_str[1][0]
    else:
        m_str = str(m)
    h_str = str(int(m))
    if len(h_str) > 1:
        h_str = ch_zh_sum(h_str)
    else:
        h_str = mydata.CH_ZH[h_str][0]
    h_str = re.sub("零+","零",h_str)
    if h_str[-1] == "零":
        return h_str[:-1],m_str
    else:
        return h_str,m_str


def dict_update(dic,data,n):
    if n == "add":
        if data[0] in dic:
            su = dic[data[0]][1] + 1
            dic.update({data[0]:(data[1],su)})
        else:
            dic.update({data[0]:(data[1],1)})
    else:
        su = dic[data[0]][1] - 1
        if su == 0:
            dic.pop(data[0])
        else:
            dic.update({data[0]:(dic[data[0]][0],su)})


def dict_date(dic,data):
    if data[0] in dic:
        #print(dic[data[0]],data[1])
        su = dic[data[0]] + data[1]
        dic.update({data[0]:su})
    else:
        dic.update({data[0]:data[1]})


def erre_log(cor):
    with open("程序错误日志.log","a",encoding="utf-8") as log:
        st = time.strftime("%Y-%m-%d %H:%M:%S") + ": :" + cor + "\n"
        log.write(st)


def get_http(auth_code,total_amount):
    timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
    method = 'alipay.trade.pay'
    app_id = ''
    sign_type='RSA'
    sign = ''
    version = '1.0'
    charset = 'utf-8'
    #biz_content = ''
    out_trade_no = time.strftime("%Y%m%d%H%M%S")     # 订单号
    subject = ''                                     # 订单标题
    scene = 'bar_code'                               # 支付场景
    auth_code = auth_code                            # 付款条形码
    total_amount = total_amount                      # 订单金额
    product_code = 'FACE_TO_FACE_PAYMENT'            # 产品码
    url = "https://openapi.alipay.com/gateway.do?timestamp={}&method={}&app_id={}&sign_type={}&sign={}&version={}&charset={}&biz_content=out_trade_no={}&subject={}&scene={}&auth_code={}&total_amount={}&product_code={}".format(timestamp,method,app_id,sign_type,sign,version,charset,out_trade_no,subject,scene,auth_code,total_amount,product_code)
    print(url)
    m = requests.get(url)
    jstxt = json.loads(m.text)
    if jstxt['code'] == '10000':
        return True
    elif jstxt['code'] == '20000':
        return get_http(auth_code,total_amount)
    else:
        return False